package com.xiaomaoguai.fcp.pre.kepler.router.rpc.httpconverter;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;
import com.xiaomaoguai.fcp.pre.kepler.router.rpc.enums.SerializerType;
import com.xiaomaoguai.fcp.pre.kepler.router.rpc.exception.SerializerException;

public class HessianSerializer implements Serializer {

	public static final String CONTENT_TYPE = "application/kepler-hessian;charset=UTF-8";

	@Override
	public Object readObject(InputStream inputStream) {
		HessianInput hessianInput = null;
		try {
			// Hessian的反序列化读取对象
			hessianInput = new HessianInput(inputStream);
			return hessianInput.readObject();
		} catch (IOException e) {
			throw new SerializerException(SerializerType.HESSIAN.name(), e);
		} finally {
			IOUtils.closeQuietly(inputStream);
			if (hessianInput != null) {
				hessianInput.close();
			}
		}
	}

	@Override
	public Object readObject(byte[] bytes) {
		ByteArrayInputStream byteArrayInputStream = null;
		HessianInput hessianInput = null;
		try {
			byteArrayInputStream = new ByteArrayInputStream(bytes);
			// Hessian的反序列化读取对象
			hessianInput = new HessianInput(byteArrayInputStream);
			return hessianInput.readObject();
		} catch (IOException e) {
			throw new SerializerException(SerializerType.HESSIAN.name(), e);
		} finally {
			IOUtils.closeQuietly(byteArrayInputStream);
			if (hessianInput != null) {
				hessianInput.close();
			}
		}
	}

	@Override
	public byte[] writeObject(Object obj) {
		ByteArrayOutputStream byteArrayOutputStream = null;
		HessianOutput hessianOutput = null;
		try {
			byteArrayOutputStream = new ByteArrayOutputStream();
			// Hessian的序列化输出
			hessianOutput = new HessianOutput(byteArrayOutputStream);
			hessianOutput.writeObject(obj);
			return byteArrayOutputStream.toByteArray();
		} catch (IOException e) {
			throw new SerializerException(SerializerType.HESSIAN.name(), e);
		} finally {
			IOUtils.closeQuietly(byteArrayOutputStream);
			if (hessianOutput != null) {
				try {
					hessianOutput.close();
				} catch (IOException e) {
				}
			}
		}
	}
}